package com.zdzx.controller.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.google.zxing.WriterException;
import com.zdzx.base.common.util.RedisUtil;
import com.zdzx.base.common.util.UserInfoUtil;
import com.zdzx.common.result.Result;
import com.zdzx.common.result.ResultCode;
import com.zdzx.common.result.ResultUtil;
import com.zdzx.mapper.CourseUserMapper;
import com.zdzx.mapper.TransactionRecordMapper;
import com.zdzx.mapper.UserMapper;
import com.zdzx.model.service.base.result.UserInfo;
import com.zdzx.model.service.base.vo.User;
import com.zdzx.model.service.content.param.PayData;
import com.zdzx.model.service.content.vo.CourseUser;
import com.zdzx.model.service.content.vo.TransactionRecord;
import com.zdzx.wx.QrCodeCreateUtil;
import com.zdzx.wx.WXPayService;
import com.zdzx.wx.WXPayUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "web支付")
@RestController()
@RequestMapping("/web")
public class WebPayController {
	
	@Autowired
	private TransactionRecordMapper transactionRecordMapper;
	@Autowired
	private CourseUserMapper courseUserMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
    private WXPayService wxPayService;
	@Autowired
	private RedisUtil redisUtil;
	
	@ApiOperation(value = "支付回调", notes = "")
    @GetMapping(value = "/pay/notifiy")
    public Object notifiy(HttpServletRequest request) {
    	Enumeration<String> parameterNames = request.getParameterNames();
    	while(parameterNames.hasMoreElements()) {
    		String nextElement = parameterNames.nextElement();
    		System.out.println("key:"+nextElement+"----value:"+request.getParameter(nextElement));
    	}
        return "";
    }
    
	@ApiOperation(value = "支付", notes = "")
    @PostMapping(value = "/pay")
    public Result<Map<String,String>> pay(@RequestBody PayData payData,
    		HttpServletRequest request) {
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if(loginInfo==null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getMes() , null);
		}
		String productId=WXPayUtil.generateUUID();
    	Double tempMoney=100*Double.parseDouble(payData.getMoney());
    	Map<String, String> doUnifiedOrder = wxPayService.doUnifiedOrder(productId,tempMoney.intValue()+"");
    	System.out.println(doUnifiedOrder);
    	if("SUCCESS".equals(doUnifiedOrder.get("result_code"))) {
    		InputStream in = null;
            byte[] data = null;
            try {
            	QrCodeCreateUtil.createQrCode(new FileOutputStream(new File(productId+".jpg")),doUnifiedOrder.get("code_url"),900,"JPEG");
                in = new FileInputStream(new File(productId+".jpg"));
                data = IOUtils.toByteArray(in);
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (WriterException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				IOUtils.closeQuietly(in);
				
			}
            String img=Base64.encodeBase64String(data); // encodeBase64String(data);
    		TransactionRecord transactionRecord=new TransactionRecord();
    		transactionRecord.setId(productId);
    		transactionRecord.setMoney(payData.getMoney());
    		//transactionRecord.setMerchantId("11"); //merchant.getId()
    		//transactionRecord.setMerchantName("22");//merchant.getName()
    		transactionRecord.setCreateTime(LocalDateTime.now());
    		transactionRecord.setUserId(loginInfo.getId());
    		transactionRecord.setUsername(StringUtils.isEmpty(loginInfo.getRealName())?loginInfo.getAccount():loginInfo.getRealName());
    		transactionRecord.setUpdateTime(LocalDateTime.now());
    		transactionRecord.setType("BUY");
    		transactionRecord.setBuyType(payData.getType());
    		transactionRecord.setCourseId(payData.getCourseId());
    		transactionRecord.setStatus("WAITING");
    		transactionRecordMapper.insert(transactionRecord);
    		Map<String,String> map=new HashMap<String, String>();
    		map.put("img", img);
    		map.put("productId", productId);
    		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, map);
    	}else {
    		return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), doUnifiedOrder.get("return_msg"), null);
    	}
    //	return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), null, null);
	}
	
	@ApiOperation(value = "查询支付", notes = "")
    @GetMapping(value = "/pay/{productId}")
    public Result<String> queryPay(@PathVariable("productId")String productId) {
		
		TransactionRecord transactionRecord = transactionRecordMapper.selectById(productId);
		if(transactionRecord==null) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "", null);
		}
		try {
			Map<String, String> doUnifiedOrder = new WXPayService().doOrderQuery(productId);
			if("SUCCESS".equals(doUnifiedOrder.get("result_code"))) {
				if("SUCCESS".equals(doUnifiedOrder.get("trade_state"))) {
					TransactionRecord entity=new TransactionRecord();
					entity.setId(productId);
					entity.setStatus("VALID");
					int updateById = transactionRecordMapper.updateById(entity);
					if(updateById>0) {
						if("1".equals(transactionRecord.getBuyType())) {
							CourseUser entityUser=new CourseUser();
							entityUser.setUserId(transactionRecord.getUserId());
							entityUser.setCourseId(transactionRecord.getCourseId());
							entityUser.setCreateTime(LocalDateTime.now());
							entityUser.setExpireTime(LocalDateTime.now().plusMonths(1L));
							courseUserMapper.insert(entityUser);
						}else {
							User entityUserInfo=new User();
							entityUserInfo.setId(transactionRecord.getUserId());
							entityUserInfo.setIsVip("1");
							userMapper.updateById(entityUserInfo);
						}
						
					}
					System.out.println(updateById>0?"保存支付成功":"保存支付失败");
				}
				System.out.println(JSON.toJSONString(doUnifiedOrder));
				return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), doUnifiedOrder.get("return_msg"),doUnifiedOrder.get("trade_state"));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), null, null);
		}
		return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), null, null);
    }
    public static void main(String[] args) throws Exception {
    	
    //	Map<String, String> doUnifiedOrder = new WXPayService().doOrderQuery("1133313-333");
    	//Map<String, String> doUnifiedOrder = new WXPayService().doUnifiedOrder("1133313-333","22");
    	//System.out.println(doUnifiedOrder);
    	System.out.println(LocalDateTime.now().plusMonths(1L));
	}
}
